package com.zsgeek.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.zsgeek.db.DBUtils;
import com.zsgeek.db.ResultSetHandler;
import com.zsgeek.entity.User;

public class AdminUserDao {

	/**
	 * 用户登录（ajax的，没用到）
	 * 
	 * @param email
	 * @param password
	 * @return 3: 账号错误；2：密码错误；1：正确
	 */
	public static String login(String email, String password) {
		String sql = "SELECT password FROM  user WHERE email = ?";
		Object obj = DBUtils.executeQuery(sql, email);
		if (obj == null) {
			return "3";
		} else {
			if (obj.toString().equals(password)) {
				return "1";
			} else {
				return "2";
			}
		}
	}
	
	/**
	 * 根据用户帐号获取用户信息
	 * 
	 * @param email
	 * @return
	 */
	public static User getUserByUserEmail(String email) {
		String sql = "SELECT userName,password,email,role FROM user WHERE email = ?";
		return (User) DBUtils.executeQuery(sql, new ResultSetHandler() {
			@Override
			public Object doHandler(ResultSet rs) throws SQLException {
				if (rs.next()) {
					User user = new User();
					user.setUserName(rs.getString(1));
					user.setPassword(rs.getString(2));
					user.setEmail(rs.getString(3));
					user.setRole(rs.getInt(4));
					return user;
				}
				return null;
			}
		}, email);
	}
	
	/**
	 * 用户注册的方法
	 * 
	 * @param user
	 * @return
	 */
	public static int register(User user) {

		String sql = "INSERT INTO user(userName,password,email,role) VALUES (?,?,?,0)";
		return  DBUtils.executeUpdate(sql, user.getUserName(),
				user.getPassword(), user.getEmail());
	}
	
	/**
	 * 修改用户信息
	 * 
	 * @param user
	 * @return
	 */
	public static boolean update(User user) {
		String sql = "UPDATE user SET  userName=?,password=? WHERE email=?";
		return DBUtils.executeUpdate(sql,user.getUserName(),
				user.getPassword(), user.getEmail()) > 0;
	}

}
